package yt.demo.appcoresystem.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import yt.demo.appcommondb.tools.ListConverter;
import yt.demo.appcommontools.utils.FileUtils;
import yt.demo.appcommontools.utils.dto.FileInfoDTO;
import yt.demo.appcommontools.utils.files.FileStorageServiceFactory;
import yt.demo.appcoresystem.entity.SystemUploadFile;
import yt.demo.appcoresystem.service.IFileService;

@Service
public class FileService implements IFileService {


    private final FileStorageServiceFactory fileFactory;

    private final SystemUploadFileService uploadFileService;

    @Autowired
    public FileService(FileStorageServiceFactory fileStorageServiceFactory, SystemUploadFileService uploadFileService) {
        this.fileFactory = fileStorageServiceFactory;
        this.uploadFileService = uploadFileService;
    }

    public String getDomainName(Integer storageMode) {
        return fileFactory.getDomainName();
    }

    @Override
    public FileInfoDTO upload(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        String fileHash = FileUtils.calculateFileHash(originalFileName);
        SystemUploadFile fileHashData = uploadFileService.getFileInfoByHash(fileHash);
        if (fileHashData != null) {
            fileHashData.setUrl(fileFactory.getDomainName() + fileHashData.getUrl());
            return ListConverter.convertOne(fileHashData, FileInfoDTO.class);
        }
        FileInfoDTO fileData = fileFactory.createFileStorageService().upload(file);
        SystemUploadFile uploadFileData = ListConverter.convertOne(fileData, SystemUploadFile.class);
        uploadFileService.create(uploadFileData);
        fileData.setUrl(fileFactory.getDomainName() + uploadFileData.getUrl());
        return fileData;
    }

    @Override
    public FileInfoDTO uploadBase64(String base64Data) {
        // 去掉数据头部分
        String base64Content = base64Data.split(",")[1];
        String fileHash = FileUtils.calculateFileHash(base64Content);
        SystemUploadFile fileHashData = uploadFileService.getFileInfoByHash(fileHash);
        if (fileHashData != null) {
            fileHashData.setUrl(fileFactory.getDomainName() + fileHashData.getUrl());
            return ListConverter.convertOne(fileHashData, FileInfoDTO.class);
        }
        FileInfoDTO fileData = fileFactory.createFileStorageService().uploadBase64(base64Data);
        SystemUploadFile uploadFileData = ListConverter.convertOne(fileData, SystemUploadFile.class);
        uploadFileService.create(uploadFileData);
        fileData.setUrl(fileFactory.getDomainName() + uploadFileData.getUrl());
        return fileData;
    }
}
